<template>
  <div
    class="watermark-container"
    v-if="shouldShowWatermark"
  >
    <div
      class="watermark-item"
      :style="{ 
        backgroundImage: `url(${watermarkImage})`,
        backgroundSize: `${watermarkWidth}px ${watermarkHeight}px`
      }"
    />
  </div>
</template>

<script>
export default {
  name: 'Watermark',
  data() {
    return {
      watermarkImage: '',
      watermarkWidth: 200, // 单个水印宽度
      watermarkHeight: 150, // 单个水印高度
      username: localStorage.getItem('username') || ''
    }
  },
  computed: {
    shouldShowWatermark() {
      // 登录页不显示水印，且只有存在用户名时才显示
      return this.$route.path !== '/login' && this.username
    },
    currentDate() {
      // 格式化当前日期为 yyyy-mm-dd
      const date = new Date()
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    watermarkText() {
      // 水印内容：用户名 + 当前日期
      return `${this.username} ${this.currentDate}`
    }
  },
  watch: {
    // 监听路由变化
    '$route.path': 'updateWatermark',
    // 监听水印文本变化
    watermarkText: 'updateWatermark'
  },
  mounted() {
    // 监听localStorage变化
    window.addEventListener('storage', this.handleStorageChange)
    this.updateWatermark()
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.handleStorageChange)
  },
  methods: {
    handleStorageChange(e) {
      if (e.key === 'username') {
        this.username = e.newValue || ''
      }
    },
    updateWatermark() {
      if (!this.shouldShowWatermark) return

      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')

      canvas.width = this.watermarkWidth
      canvas.height = this.watermarkHeight

      ctx.font = '14px Microsoft YaHei'
      ctx.fillStyle = 'rgba(0, 0, 0, 0.2)'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'

      ctx.translate(this.watermarkWidth / 2, this.watermarkHeight / 2)
      ctx.rotate(-Math.PI / 12)

      ctx.fillText(this.watermarkText, 0, 0)

      this.watermarkImage = canvas.toDataURL('image/png')
    }
  }
}
</script>

<style scoped>
.watermark-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9999;
  overflow: hidden;
}

.watermark-item {
  width: 100%;
  height: 100%;
  background-repeat: repeat;
  background-position: 0 0;
}
</style>
